﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExcelToSql.Code;
using ExcelToSql.Forms;

namespace ExcelToSql
{
    public partial class Form1 : Form
    {

        DataTable _dtLoaded;
        List<DataColumnDef> _colDefs;

        public Form1()
        {
            InitializeComponent();
        }

        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFile();
        }

        private void openFile()
        {
            OpenFileDialog ofd = null;
            ExcelProcessor xp = null;
            WorksheetSelector wsSelect;
            string worksheetName = null, selectedFile = null;
            FileInfo xlFile;

            ofd = new OpenFileDialog();
            ofd.Filter = "Excel 2007 File (*.xlsx)|*.xlsx|Excel 2003 File (*.xls)|*.xls";
            ofd.InitialDirectory = Environment.GetEnvironmentVariable("USERPROFILE");
            if (ofd.ShowDialog() != DialogResult.OK)
                return;

            selectedFile = ofd.FileName;
            xlFile = new FileInfo(selectedFile);
            xp = new ExcelProcessor(selectedFile);
            xp.OpenFile();

            if (xp.SheetNames.Length > 1)
            {
                wsSelect = new WorksheetSelector(xlFile.Name, xp.SheetNames);
                if (wsSelect.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    return;
                worksheetName = wsSelect.SelectedWorksheet;
            }
            else
                worksheetName = xp.SheetNames[0];

            _dtLoaded = xp.ParseWorksheet(worksheetName);
            _colDefs = xp.ColDefs;
            dgExcelData.DataSource = _dtLoaded;
            
        }
    }
}
